import { setToken, getToken, removeToken } from '@/utils/auth'

import { postLogin, getProfile } from '@/api/user'
const state = {
  token: getToken(),
  userInfo: {}, // 用户
  routers: []
}
const getters = {}

const mutations = {
  // 登录的token
  getToken(state, token) {
    state.token = token
  },
  // 用户
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, userRouter) {
    state.routers = userRouter
  }

}

const actions = {
  // 登录
  async login(context, data) {
    const res = await postLogin(data)
    const token = res.data
    context.commit('getToken', token)
    setToken(token)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const res = await getProfile()
    context.commit('setUserInfo', res.data)
  },
  // 退出登录
  logout(context) {
    // 清除token
    removeToken()
    // 清除用户信息
    context.commit('setUserInfo', {})
    // 清除vuex的token
    context.commit('getToken', '')
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
